<?php
namespace app;
use \Curl\Curl;
use \Curl\MultiCurl;
use think\Db;
// 应用公共文件
class common {
	/**
	 * [addTbl 向数据表中插入数据]
	 * @param [string] $table [数据表名,'stroy']
	 * @param [array] $data  [要插入的数据]  $data = array('name' => $name, 'author' => $author, 'introduction' => $introduction, 'category_id' => $category_id);
	 * @param [array] $key   [要校验的关键字] $key = array('name','author'); 
	 */
	public static function addTbl($table,$data,$key=array()){
		//参数错误，数据表名为空，新增数据为空，新增数据不是数组格式
		if(!$table || !$data || !is_array($data)){
			return false;
		}

		$map = array();
		if($key){
			foreach ($key as $m => $o) {
				$map_key = '';
				$map_key = isset($data[$o])?$data[$o]:'';
				!empty($map_key)?($map[$o] = $map_key):'';
			}
		}
		//如果有关键字段，且所有关键字段为空，表示参数错误，不允许插入数据
		if($key && empty($map)){
			return false;
		}

		$story = array();
		//校验要检查的关键字段是否有相同数据存在,存在则不新增
		if($map){
			$story = Db::table($table)->where($map)->find();
		}
		
		if($story){
			//已存在
			return false;		
		}
		//不存在则新增
		$story = Db::table($table)->insertGetId($data);
		return $story;
	}
	//$key = array('txt_id'=>$txt_id, 'name'=> $name);  $data = array('name' => $name, 'author' => $author, 'introduction' => $introduction, 'category_id' => $category_id);
	public static function updateTbl($table, $data, $key=array()){
		//参数错误，数据表名为空，修改数据为空，修改数据不是数组格式
		if(!$table || !$data || !is_array($data)){
			return false;
		}

		//修改数据
		$story = array();
		if($key){
			$story = Db::table($table)->where($key)->update($data);
		}else{
			$story = Db::table($table)->update($data);
		}		
			
		return $story;
	}
	/**
	 * [encoding 编码转化]
	 * @param  string $str           [要转化的字符]
	 * @param  string $encoding_to   [要转化的目的编码]
	 * @param  string $encoding_from [原编码]
	 * @return [type]                [description]
	 */
	public static function encoding($str='', $encoding_to="UTF-8", $encoding_from="GBK"){
		if($str){
			//已知原编码为encoding_from，转换为encoding_to
			$str = mb_convert_encoding($str, $encoding_to, $encoding_from); 
		}
		return $str;
	}
	/**
	 * [queryListEncodeing phpQuery认不清目标网页是什么编码，即找不到meta属性的时候，会默认转换成iso-8859-1的格式,所以乱码么，需要先从iso-8859-1的格式转换成utf-8的格式，再转换成GBK的格式]
	 * @param  string $str [需要转化的内容]
	 * @return [type]      [description]
	 */
	public static function queryListEncodeing($str=''){
		if($str){
			$str = mb_convert_encoding($str,'ISO-8859-1','UTF-8');
			$str = mb_convert_encoding($str,'UTF-8','GBK');
		}
		return $str;
	}
	/**
	 * [system 获取当前系统环境]
	 * @return [type] [description]
	 */
	public static function system(){
		$system = strtoupper(substr(PHP_OS,0,3))==='WIN'?'windows':'linux';
		return $system;
	}
	/**
	 * [getWeb curl的get请求方式]
	 * @param  [type] $url [连接地址]
	 * @return [type]      [description]
	 */
	public static function getWeb($url){
		$result = '';
		if($url){
			$curl = new Curl();
			$curl->get($url);

			if ($curl->error) {
			    echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
			} else {
			    echo 'Response:' . "\n";
			    $result = $curl->response;
			}
		}
		return $result;
	}
	/**
	 * [replacetxt 替换字符串中的<br>换行符，去除html标签]
	 * @param  [type] $txt [description]
	 * @return [type]      [description]
	 */
	public static function replacetxt($txt){
		if($txt){
			$txt = str_replace('<br >', "\r\n", $txt);
			$txt = str_replace('<br>', "\r\n", $txt);
			$txt = str_replace('<br />', "\r\n", $txt);
			$txt = str_replace('<br/>', "\r\n", $txt);
            $txt = str_replace('<p>', "", $txt);
            $txt = str_replace('</p>', "\r\n", $txt);
            $txt = str_replace('&#160;', " ", $txt);
			$txt = strip_tags($txt);
		}
		return $txt;
	} 

	/**
     * 创建多级目录
     * @param string $createDir 创建的目录
     * @param string $rootDir 根目录(不检查,不创建)
     * @param int    $mode 目录权限
     * @return string 目录绝对路径($rootDir.$createDir)
     */
    public static function createDirectory($createDir, $rootDir = '', $mode = 0755)
    {
        if (empty($createDir)) return $rootDir;
        
        if (is_dir($rootDir.$createDir)) return $rootDir.$createDir;
        
        if (!preg_match('#^[/\\\]#', $createDir) && !preg_match('#^[a-z]\:#i', $createDir))
        {
            $createDir = DIRECTORY_SEPARATOR.$createDir;
        }
        
        // windows平台把盘符提取出来
        if (strtolower(PHP_OS) == 'winnt' && empty($rootDir))
        {
            preg_match('#^([a-z]\:[/\\\])#i', $createDir, $match);
            $rootDir = $match[1];
            $createDir = str_replace($rootDir, '', $createDir);
        }
        
        $createDirArr = preg_split('#[/\\\]#', $createDir);
        
        $fullDir = $rootDir;
        foreach ($createDirArr as $dir)
        {
            if (empty($dir)) continue;
            
            $fullDir .= DIRECTORY_SEPARATOR.$dir;
            
            if (!is_dir($fullDir))
            {
                if (!@mkdir($fullDir, $mode))
                {
                    throw new CException(Yii::t('nlsp', 'Directory creation failed: {dirName}.', array('{dirName}'=>$fullDir)));
                }
            }
        }
        
        return realpath($fullDir);
    }
}
